/* ----------------------------------------------------------------------------------------------------------------
 * EntityManager
 * ----------------------------------------------------------------------------------------------------------------
 */
package pure.engine.entity 
{
	import flash.net.registerClassAlias;
	import flash.geom.Rectangle;
	
	import pure.engine.system.ns_despair;
	import pure.utils.DesU;
	
	use namespace ns_despair;
	
	/**
	 * @internal
	 * 
	 * 实体管理器
	 * 
	 * @author Pure
	 * 
	 */
public class EntityManager 
{
	

	ns_despair static var m_entityGroups:Object  =  { };  // 实体组
	
	ns_despair static var m_entityMap:Object  =  { };  // 识别哈希表
	
	ns_despair static var m_numAlive:int;  // 活着的实体总数
	
	ns_despair static var cachedCount:int;  // 实体id计数，最小为 1
		
	
	
	

	/**
	 * 获取同一名字的实体列表
	 * 
	 * @param name
	 */
	ns_despair static function getEntitiesByName(name:String):Array 
	{
		if (m_entityGroups[name]) 
		{
			return m_entityGroups[name].concat();
		}
		return [];
	}
	
	
	/**
	 * 获取匹配名字的实体列表
	 * 
	 * @param names
	 */
	ns_despair static function getEntitiesByNames(names:Array):Array 
	{
		var result:Array, list:Array;
		var len:int, i:int;
		var name:String;
		
		len = names.length;
		for (i = 0; i < len; i++)
		{
			name = names[i];
			list = getEntitiesByName(name);
			if (list) 
			{
				if (result) 
				{
					result = [];
				}
				result.push.apply(result, list);
			}
		}
		return result;
	}
		
	
	/**
	 * 由ID获取实体
	 * 
	 * @param ID
	 */
	ns_despair static function getEntityByID(ID:uint):Entity
	{
		return m_entityMap[ID];
	}
	
	
   /**
	* 注册
	* 
	* @param entity
	*/
	ns_despair static function register(E:Entity):void
	{
		var ID:int;
		var group:Array;
		
		if (!m_entityGroups[E.name]) 
		{
			m_entityGroups[E.name] = [];
		}
		
		ID               =  ++cachedCount;
		E.m_id           =  ID;
		m_entityMap[ID]  =  E;
		group            =  m_entityGroups[E.name];
		
		group.push(E);
		m_numAlive++;
	}	
	 
	
	/**
	 * 注销
	 * 
	 * @param entity
	 */
	ns_despair static function unregister(E:Entity):void 
	{	
		var group:Array;
		var index:int;
		
		group  =  m_entityGroups[E.name];
		index  =  group.indexOf(E);
		
		delete m_entityMap[E.m_id];
		group.splice(index, 1);
		m_numAlive--;
	}
	
	
	/**
	 * 注册成品实体
	 * 
	 * @param args
	 */
	ns_despair static function registerEntities(args:Array):void
	{
		var factoryName:String;
		var factoryType:Class;
		var len:int, i:int;
		
		len = args.length
		while (i < len)
		{
			factoryType  =  args[i];
			factoryName  =  DesU.getClassName(factoryType);
			
			registerClassAlias(factoryName, factoryType);
			i++;
		}
	}
}

}